import socket
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
import os

# 预共享的加密密钥（必须与服务器相同）
KEY = b'ThisIsASecretKey'  # 16字节密钥

def encrypt_message(data):
    """加密文件数据"""
    iv = os.urandom(16)  # 生成随机IV
    cipher = AES.new(KEY, AES.MODE_CBC, iv)
    return iv + cipher.encrypt(pad(data, AES.block_size))

# 创建TCP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 8888)
client_socket.connect(server_address)

# 读取并加密文件
# 确保 file_path 指向一个具体的文件
file_path = r'D:\Python shiyan3 yong'
try:
    with open(file_path, 'rb') as f:
        file_data = f.read()

    encrypted_data = encrypt_message(file_data)

    # 发送加密数据
    client_socket.sendall(encrypted_data)
    print("文件已加密并发送")
except FileNotFoundError:
    print(f"文件未找到: {file_path}")
except PermissionError:
    print(f"没有权限访问文件: {file_path}")
except Exception as e:
    print(f"发生未知错误: {e}")
finally:
    client_socket.close()